Truthy and Falsy
Let's consider the following JavaScript statement:
const user = { name: 'J. Script',};
if (user.name) { console.log('This user has a name!');}
We have a user object, and we want to run a console.log depending on a condition. The condition is the JavaScript expression user.name
.
Interestingly, user.name
isn't a boolean value. The user's name is neither true
nor false
. In many programming languages, this would be an illegal operation. How should the language know if some random string is sufficient or not??
In JavaScript, every value is either "truthy" or "falsy". A truthy value is one that counts as true
when it comes to conditions.
Most values in JavaScript are truthy. It's faster to list all of the falsy values:
false
null
undefined
''
(empty string)0
(and related values, like0.0
and-0
)NaN
In the code above, user.name
is a truthy value, because it's a string with at least 1 character. Every string other than ''
is truthy.
Somewhat surprisingly, []
(empty array) and {}
(empty object) are truthy values, not falsy. This means that every object/array is truthy.
Converting to boolean
Sometimes, it's beneficial to convert a truthy value into true
, or a falsy value into false
.
The most declarative way to do this is to use the Boolean()
constructor:
Boolean(4); // trueBoolean(0); // falseBoolean([]); // trueBoolean(''); // false
There's another more-common way to convert to boolean. And, if you're not familiar with it, it can look a bit funky:
!!4; // true!!0; // false!![]; // true!!''; // false
!!
isn't actually a JavaScript operator; we're repeating the NOT operator (!
) twice.
We can use !
to flip a boolean value:
!true; // false!false; // true
If we use the !
with a non-boolean value, it will flip a truthy value to false
, or a falsy value to true
:
!4; // false, since 4 is truthy!0; // true, since 0 is falsy
We can stack multiple !
operators to flip it back and forth:
!4; // false!!4; // true!!!4; // false!!!!4; // true
To break down what's going on here: Each !
is evaluated, one at a time. It's as if there were parens around each set, like this:
!(!(!4))^^ !4 resolves to `false`!(!false)^^^^^^ !false resolves to `true`!true^^^^^ !true resolves to `false`
I'm not sure why !!
has become the de facto standard way of converting to boolean; the Boolean()
constructor seems a lot more intuitive to me!